package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * 入住Service业务层处理
 *
 * @author alexis
 * @date 2025-05-22
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 判断老人是否入住
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo());
        wrapper.eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(elder)) {
            throw new BaseException("该老人已入住");
        }
        // 更新一下床位信息
        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        // 更新或者插入 老人信息
        elder = insertOrUpdateElder(bed, checkInApplyDto.getCheckInElderDto());
        // 保存合同信息

        insertContract(elder, checkInApplyDto);

        // 新增入住信息
       CheckIn checkIn= insertCheckIn(elder,checkInApplyDto);

      // 保存入住配置信息
        insertCheckInConfig(checkIn.getId(),checkInApplyDto);

    }

    @Override
    public CheckInDetailVo detail(Long id) {
        // 创建返回的VO对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        // 获取入住配置信息
        CheckIn checkIn = checkInMapper.selectById(id);
        LambdaQueryWrapper<CheckInConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CheckInConfig::getCheckInId, id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(wrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkIn,checkInConfigVo);
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);


        // 获取老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        // 属性赋值
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        BeanUtils.copyProperties(elder,checkInElderVo);
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        // 设置家属信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);

        // 合同信息
        LambdaQueryWrapper<Contract> eldWrapper = new LambdaQueryWrapper<>();
        eldWrapper.eq(Contract::getElderId,elder.getId());
        Contract contract = contractMapper.selectOne(eldWrapper);
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;
    }

    private void insertCheckInConfig(Long id, CheckInApplyDto checkInApplyDto) {

        CheckInConfig checkInConfig = new CheckInConfig();
        checkInConfig.setCheckInId(id);
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkInConfig);
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        // 属性赋值
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());

        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        // 保存
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(Elder elder, CheckInApplyDto checkInApplyDto) {
        // 创建实体类对象
        Contract contract = new Contract();
        // 属性赋值
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        String number = "HT" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(number);
        contract.setElderName(elder.getName());
        contract.setElderId(elder.getId());

        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        // 根据开始时间和当前时间判断合同是否生效
        Integer status = startDate.isAfter(LocalDateTime.now()) ? 0 : 1;
        contract.setStatus(status);

        // 调用对应的mapper 实现数据的保存
        contractMapper.insert(contract);
    }

    private Elder insertOrUpdateElder(Bed bed, CheckInElderDto checkInElderDto) {
        // 查询老人数据
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        wrapper.ne(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(wrapper);
        if (elder != null) {
            // 更新操作
            BeanUtils.copyProperties(checkInElderDto, elder); // 属性拷贝
            // 床位相应信息
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elder.setStatus(1);
            elderMapper.updateById(elder);
        } else {
            // 插入操作
            elder = new Elder();
            BeanUtils.copyProperties(checkInElderDto, elder);
            // 床位相应信息
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elder.setStatus(1);
            elderMapper.insert(elder);
        }
        return elder;
    }
}
